<template>
  <div class="mobile-take-sheet-add">
    <page-wrapper>
      <div v-loading="loading">
        <!-- 基础信息表单 -->
        <j-border class="form-border">
          <j-form layout="vertical">
            <j-form-item label="关联盘点任务" required :span="24" :contentNest="false">
              <a-select
                v-model:value="planCode"
                placeholder="请选择关联盘点任务"
                :options="planOptions"
                @select="handleSelectPlan"
                style="width: 100%"
                allowClear
              />
            </j-form-item>

            
            <j-form-item label="商品品牌" :span="24" :contentNest="false">
              <mobile-product-brand-selector v-model:value="formData.brandId" style="width: 100%" />
            </j-form-item>
            
            <!-- <j-form-item label="预先盘点单" :span="24" :contentNest="false">
              <a-auto-complete
                v-if="formData.takeStockPlanId"
                v-model:value="preSheetCode"
                placeholder="搜索预先盘点单（单据号）"
                :options="preSheetOptions"
                @search="queryPreSheet"
                @select="handleSelectPreSheet"
                style="width: 100%"
                :dropdown-style="{ width: '100%' }"
              />
              <div v-else class="placeholder-text">请先选择关联盘点任务</div>
            </j-form-item> -->
            
            <j-form-item label="仓库" :span="24" :contentNest="false">
              <a-input v-model:value="formData.scName" disabled style="font-size: 16px;" />
            </j-form-item>
            
            <j-form-item label="盘点类别" :span="24" :contentNest="false">
              <a-input v-model:value="takeTypeDesc" disabled style="font-size: 16px;" />
            </j-form-item>
            
            <j-form-item label="盘点状态" :span="24" :contentNest="false">
              <a-input v-model:value="takeStatusDesc" disabled style="font-size: 16px;" />
            </j-form-item>
            
            <j-form-item label="备注" :span="24" :contentNest="false">
              <a-textarea v-model:value="formData.description" placeholder="请输入备注信息" />
            </j-form-item>
          </j-form>
        </j-border>

        <!-- 商品列表 -->
        <div class="goods-list-container">
          <div class="toolbar">
            <a-button
              type="primary"
              :icon="h(PlusOutlined)"
              class="add-btn"
              @click="addProduct"
              v-if="formData.takeStockPlanId"
            >
              添加商品
            </a-button>
            <div v-else class="placeholder-btn">请先选择关联盘点任务</div>
          </div>

          <vxe-grid
            ref="grid"
            show-overflow
            highlight-hover-row
            row-id="id"
            :data="tableData"
            :columns="tableColumn"
            height="300"
          >
            <!-- 商品名称列 -->
            <template #productName_default="{ row, rowIndex }">
              <a-auto-complete
                v-if="!row.isFixed"
                v-model:value="row.productName"
                placeholder="搜索商品"
                :options="row.productOptions"
                @search="(e) => queryProduct(e, row)"
                @select="(e) => handleSelectProduct(rowIndex, e, row)"
                style="width: 100%;direction: rtl;"
                :dropdown-style="{ width: '500px' }"
              />
              <span v-else>{{ row.productName }}</span>
            </template>

            <!-- 盘点数量输入 -->
            <template #takeNum_default="{ row }">
              <a-input
                v-model:value="row.takeNum"
                type="number"
                class="number-input"
                @input="(e) => takeNumInput(row, e.target.value)"
              />
            </template>

            <!-- 操作列 -->
            <template #action_default="{ rowIndex, row }">
              <a-icon
                type="delete"
                class="delete-icon"
                @click="delProduct(rowIndex)"
                v-if="!row.isFixed"
              >删除</a-icon>
            </template>
          </vxe-grid>
        </div>

        <!-- 底部按钮 -->
        <div class="bottom-buttons">
          <a-button @click="closeDialog" class="cancel-btn">取消</a-button>
          <a-button type="primary" @click="submit">保存</a-button>
        </div>
      </div>
    </page-wrapper>
  </div>
</template>

<script lang="ts">
import { h, defineComponent, reactive, toRefs, watch } from 'vue';
import { PlusOutlined, DeleteOutlined } from '@ant-design/icons-vue';
import * as api from '@/api/sc/stock/take/sheet';
import * as planApi from '@/api/sc/stock/take/plan';
import * as preApi from '@/api/sc/stock/take/pre';
import { multiplePageMix } from '@/mixins/multiplePageMix';
import moment from 'moment';

export default defineComponent({
  name: 'MobileTakeSheetAdd',
  mixins: [multiplePageMix],
  setup() {
    const state = reactive({
      loading: false,
      planCode: '',
      preSheetCode: '',
      formData: {
        takeStockPlanId: '',
        brandId: '',
        preTakeStockSheetId: '',
        description: '',
        scId: '',
        scName: '',
        takeType: '',
        takeStatus: '',
        bizName: '',
      },
      takeTypeDesc: '',
      takeStatusDesc: '',
      planOptions: [],
      preSheetOptions: [],
      tableData: [],
      tableColumn: [
        { field: 'productName', title: '商品名称', width: 200, slots: { default: 'productName_default' } },
        { field: 'stockNum', title: '库存', width: 70 },
        { field: 'takeNum', title: '盘点数', width: 80, slots: { default: 'takeNum_default' } },
        { field: 'spec', title: '规格', width: 80 },
        //{ field: 'unit', title: '单位', width: 70 },
        { title: '操作', width: 50, slots: { default: 'action_default' } }
      ],
    });

    return { ...toRefs(state), h, PlusOutlined, DeleteOutlined };
  },
  created() {
    // 组件加载时预加载盘点任务选项
    this.loadPlanOptions();
  },
  watch: {
    'formData.brandId': {
      handler(newBrandId) {
        if (newBrandId && this.formData.takeStockPlanId) {
          this.loadProductsByBrandId(newBrandId);
        }
      },
      immediate: false
    }
  },
  methods: {
    // 加载盘点任务选项
    loadPlanOptions() {
      this.loading = true;
      planApi.selector({
        pageIndex: 1,
        pageSize: 999,
        available: true,
        createTimeStart: this.$utils.formatDateTime(
          this.$utils.getDateTimeWithMinTime(moment()),
        ),
        createTimeEnd: this.$utils.formatDateTime(this.$utils.getDateTimeWithMaxTime(moment())),
      }).then(res => {
        this.planOptions = res.datas.map(item => ({
          value: item.id,
          label: item.scName
        }));
      }).finally(() => {
        this.loading = false;
      });
    },
    // 空商品对象
    emptyProduct() {
      return {
        id: this.$utils.uuid(),
        productId: '',
        productCode: '',
        productName: '',
        skuCode: '',
        externalCode: '',
        unit: '',
        spec: '',
        categoryName: '',
        brandName: '',
        stockNum: '',
        takeNum: '',
        description: '',
        productOptions: [],
        products: [],
        isFixed: false
      };
    },

    // 查询盘点任务（保留该方法以兼容其他调用）
    queryPlan(queryString: string) {
      // 此方法不再用于搜索，保持空实现以兼容可能的调用
    },

    // 选择盘点任务
    handleSelectPlan(value: string) {
      if (!value) return;
      
      this.loading = true;
      planApi.get(value).then(res => {
        this.planCode = res.scName;
        this.formData.takeStockPlanId = res.id;
        this.formData.scId = res.scId;
        this.formData.scName = res.scName;
        this.formData.takeType = res.takeType;
        this.formData.takeStatus = res.takeStatus;
        this.formData.bizName = res.bizName;
        this.takeTypeDesc = this.$enums.TAKE_STOCK_PLAN_TYPE.getDesc(res.takeType);
        this.takeStatusDesc = this.$enums.TAKE_STOCK_PLAN_STATUS.getDesc(res.takeStatus);
        
        // 清空预先盘点单
        this.formData.preTakeStockSheetId = '';
        this.preSheetCode = '';
        
        // 加载盘点任务商品
        planApi.getProducts(value).then(products => {
          this.tableData = products.map(item => {
            return Object.assign(this.emptyProduct(), { isFixed: false }, item);
          });
        });
      }).finally(() => {
        this.loading = false;
      });
    },

    // 搜索预先盘点单
    queryPreSheet(queryString: string) {
      if (!queryString || !this.formData.takeStockPlanId) {
        this.preSheetOptions = [];
        return;
      }
      preApi.searchSheets({ code: queryString, scId: this.formData.scId }).then(res => {
        this.preSheetOptions = res.map(item => ({
          value: item.id,
          label: item.code
        }));
      });
    },

    // 选择预先盘点单
    handleSelectPreSheet(value: string) {
      if (!value || !this.formData.takeStockPlanId) return;
      
      this.loading = true;
      preApi.getProducts(value, this.formData.takeStockPlanId).then(products => {
        products.forEach(item => {
          const existingProduct = this.tableData.find(obj => obj.productId === item.productId);
          if (existingProduct) {
            existingProduct.takeNum = item.takeNum;
          } else {
            this.tableData.push(Object.assign(this.emptyProduct(), item));
          }
        });
        
        // 获取预先盘点单详情，设置编码
        preApi.get(value).then(sheetRes => {
          this.preSheetCode = sheetRes.code;
          this.formData.preTakeStockSheetId = value;
        });
      }).finally(() => {
        this.loading = false;
      });
    },

    // 添加商品
    addProduct() {
      if (!this.formData.takeStockPlanId) {
        this.$msg.createError('请先选择关联盘点任务');
        return;
      }
      this.tableData.push(this.emptyProduct());
    },

    // 搜索商品
    queryProduct(queryString: string, row: any) {
      if (!queryString || !this.formData.takeStockPlanId) {
        row.productOptions = [];
        return;
      }
      api.searchProducts(this.formData.takeStockPlanId, queryString).then(res => {
        row.products = res;
        row.productOptions = res.map((item: any) => ({
          value: item.productId,
          label: `${item.productName} ${item.productCode}`
        }));
      });
    },

    // 选择商品
    handleSelectProduct(index: number, value: string, row: any) {
      value = row ? row.products.find((item: any) => item.productId === value) : value;
      
      // 检查重复
      for (let i = 0; i < this.tableData.length; i++) {
        const data = this.tableData[i];
        if (data.productId === value.productId && i !== index) {
          this.$msg.createError('商品已存在，请勿重复添加');
          this.tableData.splice(index, 1);
          return;
        }
      }
      
      this.tableData[index] = Object.assign(this.tableData[index], value);
    },

    // 删除商品
    delProduct(index: number) {
      if (this.tableData[index].isFixed) {
        this.$msg.createError('固定商品不允许删除');
        return;
      }
      this.tableData.splice(index, 1);
    },
    
    // 根据品牌ID加载商品
    loadProductsByBrandId(brandId) {
      if (!brandId) return;
      
      this.loading = true;
      api.queryProductList({
        pageIndex: 1,
        pageSize: 99999,
        brandId: brandId,
        planId: this.formData.takeStockPlanId
      }).then(res => {
        // 清空现有商品（保留固定商品）
        const fixedProducts = this.tableData.filter(item => item.isFixed);
        this.tableData = [...fixedProducts];
        
        // 添加品牌下的所有商品
        if (res.datas && res.datas.length > 0) {
          res.datas.forEach(item => {
            // 检查是否已存在该商品
            const exists = this.tableData.some(tableItem => tableItem.productId === item.productId);
            if (!exists) {
              const newProduct = this.emptyProduct();
              newProduct.productId = item.productId;
              newProduct.productCode = item.productCode;
              newProduct.productName = item.productName;
              newProduct.skuCode = item.skuCode;
              newProduct.externalCode = item.externalCode;
              newProduct.unit = item.unit;
              newProduct.spec = item.spec;
              newProduct.categoryName = item.categoryName;
              newProduct.brandName = item.brandName;
              newProduct.stockNum = item.stockNum || '0';
              newProduct.takeNum = '';
              this.tableData.push(newProduct);
            }
          });
        }
      }).finally(() => {
        this.loading = false;
      });
    },

    // 盘点数量输入事件
    takeNumInput(row: any, value: string) {
      row.takeNum = value;
    },

    // 验证表单
    validParams() {
      if (!this.formData.takeStockPlanId) {
        this.$msg.createError('请选择关联盘点任务！');
        return false;
      }
      if (this.tableData.length === 0) {
        this.$msg.createError('请录入商品！');
        return false;
      }

      for (let i = 0; i < this.tableData.length; i++) {
        const column = this.tableData[i];
        if (!column.productId) {
          this.$msg.createError('第' + (i + 1) + '行商品不允许为空！');
          return false;
        }
        if (!column.takeNum) {
          this.$msg.createError('第' + (i + 1) + '行商品的盘点数量不允许为空！');
          return false;
        }

        if (!this.$utils.isIntegerGeZero(column.takeNum)) {
          this.$msg.createError('第' + (i + 1) + '行商品的盘点数量不允许小于0！');
          return false;
        }
      }

      return true;
    },

    // 提交表单
    submit() {
      if (!this.validParams()) {
        return;
      }
      
      const params = {
        planId: this.formData.takeStockPlanId,
        preSheetId: this.formData.preTakeStockSheetId || '',
        description: this.formData.description,
        products: this.tableData.map((item: any) => ({
          productId: item.productId,
          takeNum: item.takeNum,
          description: item.description,
        })),
      };

      this.loading = true;
      api
        .create(params)
        .then(() => {
          this.$msg.createSuccess('保存成功！');
          this.closeDialog();
        })
        .finally(() => {
          this.loading = false;
        });
    },

    // 关闭页面
    closeDialog() {
      this.$router.go(-1);
    },
  },
});
</script>

<style scoped lang="less">
.mobile-take-sheet-add {
  padding: 12px;
  font-size: 16px; // 增加基础字体大小
  min-height: 100vh;
  box-sizing: border-box;
  overflow-y: auto;
  -webkit-overflow-scrolling: touch;

  // 表单相关样式
  .form-border {
    margin-bottom: 15px;
    padding: 10px;
  }

  .ant-form-item-label > label {
    font-size: 16px; // 表单标签字体大小
  }

  // 商品列表样式
  .goods-list-container {
    margin-bottom: 15px;

    .toolbar {
      margin-bottom: 10px;
      text-align: right;
    }

    .add-btn {
      width: 100%;
      font-size: 16px; // 添加按钮字体大小
      height: 44px;
    }
  }

  // 占位文本样式
  .placeholder-text,
  .placeholder-btn {
    width: 100%;
    height: 40px;
    line-height: 40px;
    text-align: center;
    color: #999;
    background-color: #f5f5f5;
    border-radius: 6px;
    font-size: 14px;
  }

  // 表格样式调整
  :deep(.vxe-table) {
    font-size: 16px; // 表格字体大小
  }

  // 底部按钮样式
  .bottom-buttons {
    display: flex;
    justify-content: space-between;
    padding-bottom: 80px; // 增加底部间距，避免被手机浏览器工具栏遮挡
    button {
      width: 48%;
      font-size: 18px; // 底部按钮字体大小
      height: 44px;
    }

    .cancel-btn {
      background: #f5f5f5;
      border-color: #d9d9d9;
    }
  }

  // 输入框样式
  .number-input {
    width: 100%;
    font-size: 16px; // 数字输入框字体大小
  }

  // 自动完成组件样式
  :deep(.ant-auto-complete) .ant-input {
    font-size: 16px; // 自动完成输入框字体大小
  }

  // 删除图标样式
  .delete-icon {
    color: #f5222d;
    cursor: pointer;
    font-size: 16px; // 删除图标旁边文本字体大小
  }
}
</style>